package com.aqie.medium.stack;

import java.util.Stack;

/**
 * 1003 替换后字符串是否有效
 */
public class IsValid {
    public static boolean isValid(String S) {
        int l = S.length();
        if (l % 3 != 0) return false;

        Stack<Character> stack = new Stack<>();
        char pre, prepre;
        for (int i = 0; i < l; i++){
            if (stack.size() >= 2){
               pre = stack.peek();
               stack.pop();
               prepre = stack.peek();
               if (prepre == 'a' && pre == 'b' && S.charAt(i) == 'c'){
                   stack.pop();
                   continue;
               }
               stack.push(pre);
               stack.push(S.charAt(i));
            }else {
                stack.push(S.charAt(i));
            }
        }
        return stack.empty();
    }

    public static void main(String[] args) {
        String s = "abc";
        System.out.println(isValid(s));
        s = "abcabcababcc";
        System.out.println(isValid(s));
        s = "aabcbc";
        System.out.println(isValid(s));
    }

}
